<?php
namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller {
    /**
     * 登录主页
     * @return [type] [description]
     */
    public function BaseController(){
        //设置字符集
        header("Content-Type:text/html; charset=utf-8");
        $this->display();
    }
    /**
     * 登录验证
     * @return [type] [description]
     */
    public function login(){
        //设置字符集
        header("Content-Type:text/html; charset=utf-8");
        if(!IS_POST)$this->error("非法请求");
        $member = M('user');
        $username =I('username');
        $password =md5(I('password'));
        $code = I('verify','','strtolower');
        //验证验证码是否正确
        if(!($this->check_verify($code))){
            $this->error('验证码错误');
        }
        //验证账号密码是否正确
        $user = $member->where("username = '%s' and password= '%s'",array($username,$password))->find();

        if(!$user) {
            $this->error('账号或密码错误 :(') ;
        }
        //验证账户是否被禁用
        if($user['status'] == 0){
            $this->error('账号被禁用，请联系超级管理员 :(') ;
        }
        
        //判断管理者的权限
        
        if($user['status'] == 1 || $user['status'] == 2){
            $data =array(
                'id' => $user['id'],
                'log_time' => time(),
                'login_ip' => get_client_ip(),
            );
            
            //如果数据更新成功  跳转到后台主页
            if($member->save($data)){
                session('adminId',$user['id']);
                session('username',$user['username']);
            $this->success("恭喜您登陆管理系统成功",U('Ent/index'));
            }
        }
        
    }
    /**
     * 验证码
     * @return [type] [description]
     */
    public function verify(){
        //设置字符集
        header("Content-Type:text/html; charset=utf-8");
        $Verify = new \Think\Verify();
        $Verify->codeSet = '0123456789';
        $Verify->fontSize = 13;
        $Verify->length = 4;
        $Verify->entry();
    }
    /**
     * 验证
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    protected function check_verify($code){
        //设置字符集
        header("Content-Type:text/html; charset=utf-8");
        $verify = new \Think\Verify();
        return $verify->check($code);
    }
    /**
     * 登录退出
     * @return [type] [description]
     */
    public function logout(){
        //设置字符集
        header("Content-Type:text/html; charset=utf-8");
        session('adminId',null);
        session('username',null);
        redirect(U('Login/index'));
    }
        
}